package reduce.fz.com.reduce.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.util.SparseArrayCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.TextView;

import com.alibaba.fastjson.TypeReference;

import reduce.fz.com.reduce.R;
import reduce.fz.com.reduce.abstracts.AbResponseListener;
import reduce.fz.com.reduce.bean.Team;
import reduce.fz.com.reduce.bean.result.Result;
import reduce.fz.com.reduce.custom.LoadingDialog;
import reduce.fz.com.reduce.custom.NetworkImageView;
import reduce.fz.com.reduce.custom.SlidingTabLayout;
import reduce.fz.com.reduce.custom.TouchCallbackLayout;
import reduce.fz.com.reduce.custom.pagerheader.ScrollableFragmentListener;
import reduce.fz.com.reduce.custom.pagerheader.ScrollableListener;
import reduce.fz.com.reduce.custom.pagerheader.ViewPagerHeaderHelper;
import reduce.fz.com.reduce.custom.pagerheader.ViewPagerHeaderHelper.OnViewPagerTouchListener;
import reduce.fz.com.reduce.fragment.base.BaseFragment;
import reduce.fz.com.reduce.service.TeamService;
import reduce.fz.com.reduce.util.HttpUtils;
import reduce.fz.com.reduce.util.ServiceBuilder;

public class TeamDetailFragment extends BaseFragment implements ScrollableFragmentListener {
    private Long teamid;
    private Team team;
    private NetworkImageView mIvTeamImage;
    private TextView mTeamTitle;
    private TextView mTeamDesc;
    private TextView mTvKeeyDays;
    private TextView mTvJoinNum;
    private TextView mTvCompleteNum;
    private View view;
    private TeamService teamService = ServiceBuilder.builderTeamService(null);
    //存储viewpage中的fragment
    private SparseArrayCompat<ScrollableListener> mScrollableListenerArrays = new SparseArrayCompat<ScrollableListener>();
    //viewPager中的tab选项高度
    private int mTabHeight;
    //teamHeder高度
    private int mHeaderHeight;

    //viewPager辅助
    private ViewPagerHeaderHelper mViewPagerHeaderHelper;
    //viewPager对象
    private ViewPager mViewPager;
    //teamHeader对象
    private View mHeaderLayoutView;
    private Interpolator mInterpolator = new DecelerateInterpolator();

    @Override
    public void onFragmentAttached(ScrollableListener fragment, int position) {
        mScrollableListenerArrays.put(position, fragment);
    }

    @Override
    public void onFragmentDetached(ScrollableListener fragment, int position) {
        mScrollableListenerArrays.remove(position);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        teamid = (Long) getArguments().getLong("teamid");
    }

    /**
     * 初始化入口
     *
     * @param view
     */
    public void init(View view) {

        loadTeam(teamid);

    }


    private class ViewPagerAdapter extends FragmentPagerAdapter {

        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public android.support.v4.app.Fragment getItem(int position) {
            BaseViewPagerFragment fragment = null;
            switch (position) {
                case 0: {
                }
                case 1: {
                    fragment = TeamDynamicFragment.create(team);
                    break;
                }
                case 2: {
                    fragment = TeamSubjectFragment.create(team);
                }
                default:
                    break;

            }
            fragment.setListener(TeamDetailFragment.this);
            return fragment;
        }

        @Override
        public int getCount() {
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "我的";
                case 1:
                    return "动态";
                case 2:
                    return "话题";
            }
            return "";
        }
    }


    /**
     * 判断应该现实哪个页签
     *
     * @return
     */
    public int getDisplyIndex() {
        if (team.teamAttach.isJoin)
            return 1;
        else return 2;
    }


    public void initMainWidget(View view) {
        mTabHeight = getResources().getDimensionPixelSize(R.dimen.tabs_height);
        mHeaderHeight = getResources().getDimensionPixelSize(R.dimen.viewpager_header_height);
        mHeaderLayoutView = view.findViewById(R.id.team_detail_viewpage);
        mViewPager = (ViewPager) view.findViewById(R.id.team_detail_viewpage);
        SlidingTabLayout slidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.team_tabs);
        mViewPager.setAdapter(new ViewPagerAdapter(getChildFragmentManager()));
        mViewPager.setOffscreenPageLimit(2);
        slidingTabLayout.setViewPager(mViewPager);
        ViewCompat.setTranslationY(mViewPager, mHeaderHeight);
        mViewPager.setCurrentItem(getDisplyIndex());
        mViewPagerHeaderHelper = new ViewPagerHeaderHelper(getActivity(), new OnViewPagerTouchListener() {
            @Override
            public boolean isViewBeingDragged(MotionEvent event) {
                return mScrollableListenerArrays.valueAt(mViewPager.getCurrentItem()).isViewBeingDragged(event);
            }

            @Override
            public void onMoveStarted(float eventY) {

            }


            @Override
            public void onMove(float eventY, float yDx) {
                float headerTranslationY = ViewCompat.getTranslationY(mHeaderLayoutView) + yDx;
                if (headerTranslationY >= 0) { // pull end
                    headerExpand(0L);


                } else if (headerTranslationY <= -mHeaderHeight) { // push end
                    headerFold(0L);
                } else {
                    ViewCompat.animate(mHeaderLayoutView)
                            .translationY(headerTranslationY)
                            .setDuration(0)
                            .start();
                    ViewCompat.animate(mViewPager)
                            .translationY(headerTranslationY + mHeaderHeight)
                            .setDuration(0)
                            .start();
                }
            }

            @Override
            public void onMoveEnded(boolean isFling, float flingVelocityY) {

            }
        });

        TouchCallbackLayout touchCallbackLayout = (TouchCallbackLayout) view.findViewById(R.id.touch_layout);
        touchCallbackLayout.setTouchEventListener(new TouchCallbackLayout.TouchEventListener() {
            @Override
            public boolean onLayoutInterceptTouchEvent(MotionEvent ev) {
                return mViewPagerHeaderHelper.onLayoutInterceptTouchEvent(ev,
                        mTabHeight + mHeaderHeight);
            }

            @Override
            public boolean onLayoutTouchEvent(MotionEvent ev) {
                return mViewPagerHeaderHelper.onLayoutTouchEvent(ev);
            }
        });
    }

    /**
     * team 头部展开
     *
     * @param duration
     */
    private void headerExpand(long duration) {
        ViewCompat.animate(mHeaderLayoutView)
                .translationY(0)
                .setDuration(duration)
                .setInterpolator(mInterpolator)
                .start();

        ViewCompat.animate(mViewPager)
                .translationY(mHeaderHeight)
                .setDuration(duration)
                .setInterpolator(mInterpolator)
                .start();
        mViewPagerHeaderHelper.setHeaderExpand(true);
    }

    /**
     * team 头部隐藏
     *
     * @param duration
     */
    private void headerFold(long duration) {
        ViewCompat.animate(mHeaderLayoutView)
                .translationY(-mHeaderHeight)
                .setDuration(duration)
                .setInterpolator(mInterpolator)
                .start();

        ViewCompat.animate(mViewPager).translationY(0).
                setDuration(duration).setInterpolator(mInterpolator).start();

        mViewPagerHeaderHelper.setHeaderExpand(false);
    }

    /**
     * 获取team详情
     *
     * @param teamid
     */
    public void loadTeam(Long teamid) {
        final LoadingDialog dialog = new LoadingDialog(getActivity());
        dialog.show();
        teamService.loadTeamDetail(teamid, new AbResponseListener<Team>(new TypeReference<Result<Team>>() {
        }) {
            @Override
            public void responseInfo(Result<Team> data) {
                dialog.dismiss();
                team = data.getData();
                initMainWidget(view);
                initTeamHeaderView(view);
                initTeamHeaderData();
            }
        });
    }

    /**
     * 初始化team header
     *
     * @param view
     */
    public void initTeamHeaderView(View view) {
        mIvTeamImage = (NetworkImageView) view.findViewById(R.id.nv_team_image);
        mTeamTitle = (TextView) view.findViewById(R.id.tv_team_title);
        mTeamDesc = (TextView) view.findViewById(R.id.tv_team_desc);
        mTvKeeyDays = (TextView) view.findViewById(R.id.tv_keep_days);
        mTvJoinNum = (TextView) view.findViewById(R.id.tv_joinnum);
        mTvCompleteNum = (TextView) view.findViewById(R.id.tv_complete_num);
    }

    /**
     * 填充teamheader数据
     */
    public void initTeamHeaderData() {
        mIvTeamImage.setImageUrl(team.iconurl, HttpUtils.getImageLoader());
        mTeamTitle.setText(team.title);
        mTeamDesc.setText(team.desc);
        mTvKeeyDays.setText(team.needdays + "");
    }


    public TeamDetailFragment() {
    }

    public static TeamDetailFragment create(Long teamid) {
        Bundle bundle = new Bundle();
        bundle.putLong("teamid", teamid);
        TeamDetailFragment detailFragment = new TeamDetailFragment();
        detailFragment.setArguments(bundle);
        return detailFragment;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_team_detail, container, false);
        this.view = view;
        init(view);
        return view;
    }


}
